package fop;

import fop.WordToFoWithImageConverter;
import org.apache.fop.apps.*;
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.converter.WordToFoConverter;
import org.apache.poi.hwpf.converter.WordToHtmlUtils;
import org.apache.poi.util.XMLHelper;

import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * @author caiwl
 * @date 2020/10/29 10:44
 */
public class Office {

    public static void main(String[] args) throws Exception {
        String baseDir = "C:\\Caiwl\\JetBrains\\IdeaProjects\\oschina\\wife\\src\\main\\resources\\fop";
        OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(baseDir,"myfile.pdf")));
        try {
            HWPFDocumentCore document = WordToHtmlUtils.loadDoc(new File(baseDir, "互联网应用开发中心版本管理规范.doc"));
            WordToFoConverter wordToFoConverter = new WordToFoWithImageConverter(XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument());
            wordToFoConverter.processDocument(document);
            Source src = new DOMSource(wordToFoConverter.getDocument());

            FopFactory fopFactory = FopFactory.newInstance(new File(baseDir,"fop.xconf"));
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
            Result res = new SAXResult(fop.getDefaultHandler());

            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(src, res);

            // Result processing
            FormattingResults foResults = fop.getResults();
            java.util.List pageSequences = foResults.getPageSequences();
            for (Object pageSequence : pageSequences) {
                PageSequenceResults pageSequenceResults = (PageSequenceResults) pageSequence;
                System.out.println("PageSequence "
                        + (String.valueOf(pageSequenceResults.getID()).length() > 0
                        ? pageSequenceResults.getID() : "<no id>")
                        + " generated " + pageSequenceResults.getPageCount() + " pages.");
            }
            System.out.println("Generated " + foResults.getPageCount() + " pages in total.");
        } finally {
            out.close();
        }
    }
}
